package chatclient.applets.canvas;

import chatclient.applets.note.Note;
import chatclient.tools.NoteContainer;
import chatclient.tools.NoteListener;
import chatclient.applets.components.Border;
import chatclient.netio.AttrList;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;

public class ViewHeader extends ChatCanvas
        implements NoteListener {

    public ViewHeader(NoteContainer notecontainer, String s, String s1) {
        this(notecontainer, s, s1, null, true);
    }

    public ViewHeader(NoteContainer notecontainer, String s, String s1, boolean flag) {
        this(notecontainer, s, s1, null, flag);
    }

    public ViewHeader(NoteContainer notecontainer, String s, String s1, Border border1) {
        this(notecontainer, s, s1, border1, true);
    }

    public ViewHeader(NoteContainer notecontainer, String s, String s1, Border border1, boolean flag) {
        super(notecontainer, s);
        sync = new Object();
        template = s1;
        border = border1;
        wrap = flag;
        attrs = null;
        addComponentListener(this);
    }

    public AttrList getAttrs() {
        return attrs;
    }

    public void setAttrs(AttrList attrlist) {
        synchronized (sync) {
            if (attrs != attrlist) {
                attrs = attrlist;
                updateNote();
            }
        }
    }

    private void updateNote() {
        note = Note.fromTemplate(this, getContainer(), size().width, template, null, attrs == null ? new AttrList() : attrs, getFont(), getFontMetrics(getFont()));
        if (note != null && border != null) {
            note.setBorder(border);
        }
        updateNoteWidth();
        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        return note == null ? new Dimension(0, 0) : new Dimension(note.getWidth(), note.getHeight());
    }

    private void updateNoteWidth() {
        if (note != null && note.getWidth() != size().width && wrap) {
            note.setWidth(size().width);
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        
        super.paintComponent(g);
        
        if (note != null) {
            note.paint(g, 0, 0, getStyle(), true);
        }
    }

    @Override
    public void noteHeightChanged(Note note1) {
        updateSize();
        super.noteHeightChanged(note1);
    }

    @Override
    public void componentResized(ComponentEvent componentevent) {
        updateNoteWidth();
        repaint();
    }
    
    private final Object sync;
    private String template;
    private Border border;
    private boolean wrap;
    private AttrList attrs;
    private Note note;


}
